import axios from 'axios'
import {Loading} from 'element-ui'

axios.defaults.withCredentials = true
export const request = (config) => {
  return axios(config)
}

let loading;
//内存中正在请求的数量
let loadingNum=0;
function startLoading() {
  if(loadingNum==0){
    loading = Loading.service({
      lock: true,
      text: '加载中...',
      background:'rgba(255,255,255,0.5)',
      target:document.querySelector('.route_div')
    })
  }
  //请求数量加1
  loadingNum++;
}
function endLoading() {
  //请求数量减1
  loadingNum--
  if(loadingNum<=0){
    loading.close()
  }
}

// 请求前设置header
axios.interceptors.request.use(
  config => {
    let url = config.url
    if (url.indexOf('admin/wx/msg')==-1){
      startLoading();
    }
    config.headers.token = window.vm.$cookies.get('token')
    return config
  },
  error => {
    return Promise.reject(error)
  })
//响应拦截器
axios.interceptors.response.use(response => {
  let url = response.config.url
  if (url.indexOf('admin/wx/msg')==-1){
    endLoading();
  }
  if (response.data.code==3 || response.data.code==1003){
    window.vm.$cookies.remove('token')
    const cr = window.vm.$router.currentRoute
    showLogin();
    // var rn = cr.name
    // var rp = cr.query
    // window.vm.$router.push({
    //   name: 'login',
    //   query: {
    //     // redirect: to.fullPath,
    //     redirect: rn,
    //     param: JSON.stringify(rp)
    //   }
    // })
    return
  }
  return response
}, error => {
  endLoading();
  return Promise.resolve(error.response)
})
export default axios
